package com.inet.receiver;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.provider.Settings;

import com.inet.baidu.MyLocationListener;
import com.inet.consoleservices.MyApplication;
import com.inet.request.ServerRequest;
import com.inet.util.AMapUri;
import com.inet.util.Gps;
import com.inet.util.HttpUtil;
import com.inet.util.L;
import com.inet.util.PositionUtil;
import com.inet.util.Utils;

public class PushOption {

	private static String gaoDePackageName = "com.autonavi.amapauto";

	/**
	 * 获取车机的当前位置
	 * 
	 * @param pContext
	 */
	public static void getCarPoint(Context pContext) {
		String lon = String.valueOf(MyLocationListener.lon);
		String lat = String.valueOf(MyLocationListener.lat);
		Map<String, String> maps = new HashMap<String, String>();
		maps.put("lon", lon);
		maps.put("lat", lat);
		String point = org.json.simple.JSONObject.toJSONString(maps);
		String speed = String.valueOf(MyLocationListener.speed);
		ServerRequest.uploadCarPoint(point, Utils.getImei(pContext), speed);
	}

	/**
	 * 远程关机
	 * 
	 * @param pContext
	 */
	public static void closeSystem(JSONObject obj, Context pContext) {
		String imei = "";
		try {
			imei = obj.getString("imei");
		} catch (JSONException e) {
			L.i("解析JSON出错......");
		}
		ServerRequest.startSuccess(Utils.getImei(pContext), "true",
				Utils.getPropertiesValue("post_pushCloseSystem"));
		// 发送关机广播
		Intent closeSystemIntent = new Intent(
				"coogo.intent.action.SHUTDOWN_ACTION");
		pContext.sendBroadcast(closeSystemIntent);
	}

	/**
	 * 启动预约导航
	 * 
	 * @param obj
	 * @param pContext
	 */
	public static void startNav(JSONObject obj, Context pContext) {
		L.i("startNav");

		Intent remoteCommandIntent = new Intent("action.colink.remotecommand");
		String text = "";
		float cLat = 0, cLng = 0;
		try {
			cLat = Float.valueOf(obj.getString("lat"));
			cLng = Float.valueOf(obj.getString("lon"));
			L.i("cLat==>" + cLat + "====cLng==>" + cLng);
			text = obj.getString("text");
		} catch (Exception e) {
			e.printStackTrace();
		}
		remoteCommandIntent.putExtra("type", "navigation");
		remoteCommandIntent.putExtra("lat", cLat);
		remoteCommandIntent.putExtra("lng", cLng);
		remoteCommandIntent.putExtra("address", text);
		pContext.sendBroadcast(remoteCommandIntent);

	}

	/**
	 * 启动好友接人
	 * 
	 * @param obj
	 * @param pContext
	 */
	public static void startFriendNav(JSONObject obj, Context pContext) {
		L.i("startFriendNav");
		Double dLat, dLng;
		try {
			dLat = Double.valueOf(obj.getString("lat"));
			dLng = Double.valueOf(obj.getString("lon"));
			startNavi(pContext, dLat, dLng, "", obj);

			// 反馈状态给服务器
			ServerRequest.startSuccess(Utils.getImei(pContext), "success",
					Utils.getPropertiesValue("post_pushShowWay"));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 打开电子围栏
	 * 
	 * @param obj
	 * @param pContext
	 */
	public static void openCrawl(JSONObject obj, Context pContext) {
		L.i("openCrawl");
		MyLocationListener.isOpenCrawal = true;
		int radius = 2000;
		try {
			radius = obj.getInt("radius");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		MyLocationListener.radius = radius;
		MyLocationListener.crawlCenterLon = MyLocationListener.lon;
		MyLocationListener.crawlCenterLat = MyLocationListener.lat;
		L.i("MyLocationListener.crawlCenterLon,crawlCenterLat==("
				+ MyLocationListener.crawlCenterLon + ","
				+ MyLocationListener.crawlCenterLon + ")");
		// 开启成功，回馈状态给服务器
		if (MyLocationListener.isOpenCrawal) {
			ServerRequest.startSuccess(Utils.getImei(pContext), "true",
					Utils.getPropertiesValue("post_pushStartCrawl"));
		}
	}

	/**
	 * 关闭电子围栏
	 * 
	 * @param obj
	 * @param pContext
	 */
	public static void closeCrawl(JSONObject obj, Context pContext) {
		L.i("closeCrawl");
		MyLocationListener.isOpenCrawal = false;
		if (!MyLocationListener.isOpenCrawal) {
			if (MyLocationListener.isOpenCrawal) {
				ServerRequest.startSuccess(Utils.getImei(pContext), "false",
						Utils.getPropertiesValue("post_pushCloseCrawl"));
			}
		}
	}

	// 旧版高德地图好友接人启动
	private static void startNavi(Context context, double toLat, double toLng,
			String name, int style, int dev) {
		AMapUri uri = new AMapUri("navi");
		uri.addParam("sourceApplication", "uniCarSolution");
		uri.addParam("poiname", name);
		uri.addParam("lat", toLat);
		uri.addParam("lon", toLng);
		uri.addParam("dev", dev);
		uri.addParam("style", style);
		String dat = uri.getDatString();
		Intent intent = new Intent();
		intent.addCategory(Intent.CATEGORY_DEFAULT);
		intent.setPackage("com.autonavi.minimap");
		intent.setData(Uri.parse(dat));
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}

	/**
	 * 好友接人启动 0百度 1高德 2凯立德 3美行
	 * 
	 * @param mContext
	 * @param lat
	 * @param lng
	 * @param address
	 * @param obj
	 */
	private static void startNavi(final Context mContext, double lat,
			double lng, String address, JSONObject obj) {
		int mapIndex = Settings.System.getInt(mContext.getContentResolver(),
				"MAP_INDEX", 0);
		L.i("mapIndex = " + mapIndex);
		switch (mapIndex) {
		case 1:
			if (Utils.checkApkExist(mContext, gaoDePackageName)) {

				String cat = "android.intent.category.DEFAULT";
				String dat = "androidauto://navi?sourceApplication=TXZAssistant&lat="
						+ lat + "&lon=" + lng + "&dev=0&style=2";
				Intent i = new Intent();
				i.setData(android.net.Uri.parse(dat));
				i.setPackage(gaoDePackageName);
				i.addCategory(cat);
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
						| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
				mContext.startActivity(i);

			} else {
				Gps gcj02 = PositionUtil.bd09_To_Gcj02(lat, lng);
				startNavi(mContext, gcj02.getWgLat(), gcj02.getWgLon(),
						address, 2, 0);
			}

			break;
		case 2:
			Intent remoteCommandIntent = new Intent(
					"action.colink.command_showway_cld");
			String text = "";
			float cLat = 0,
			cLng = 0;
			try {
				cLat = Float.valueOf(obj.getString("lat"));
				cLng = Float.valueOf(obj.getString("lon"));
				L.i("cLat==>" + cLat + "====cLng==>" + cLng);
				text = obj.getString("text");
			} catch (Exception e) {
				e.printStackTrace();
			}
			remoteCommandIntent.putExtra("type", "navigation");
			remoteCommandIntent.putExtra("lat", cLat);
			remoteCommandIntent.putExtra("lng", cLng);
			remoteCommandIntent.putExtra("address", text);
			mContext.sendBroadcast(remoteCommandIntent);
			break;
		case 3:
			Gps gcj022 = PositionUtil.bd09_To_Gcj02(lat, lng);
			Intent MXintent = new Intent("com.mxnavi.mxnavi.PTT_DEST_ACTION");
			String dest_string = "(TND,2,0, " + gcj022.getWgLat() + ","
					+ gcj022.getWgLon() + "," + "" + ")";
			MXintent.putExtra("data", dest_string);
			MXintent.setFlags(32);
			mContext.sendBroadcast(MXintent);
			break;
		default:
			Intent intent = new Intent();
			intent.setData(Uri.parse("bdnavi://plan?dest=" + lat + "," + lng
					+ "," + address + ")"));
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
					| Intent.FLAG_ACTIVITY_SINGLE_TOP);
			mContext.startActivity(intent);
			break;
		}

	}

	/**
	 * 收到拍照指令，发送广播给Camera
	 * 
	 * @param obj
	 * @param pContext
	 */
	public static void getPhoto(JSONObject obj, Context pContext) {
		Intent photoIntent = new Intent(MyBroadcastReceiver.ASK_FOR_PICTURE);
		String openId = null;
		String pushTime = null;
		L.i("pushOption obj=" + obj.toString());
		try {
			openId = obj.getString("openId");
			L.i("pushOption openId==" + openId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Bundle pBundle = new Bundle();
		pBundle.putString("OPEN_ID", openId);
		photoIntent.putExtras(pBundle);
		pContext.sendBroadcast(photoIntent);
	}

	/**
	 * 收到视频指令，发送广播给Camera
	 * 
	 * @param obj
	 * @param pContext
	 */
	public static void getVideo(JSONObject obj, Context pContext) {
		Intent videoIntent = new Intent(MyBroadcastReceiver.ASK_FOR_VEDIO);
		String openIdStr = null;
		try {
			openIdStr = obj.getString("openId");
		} catch (Exception e) {
			e.printStackTrace();
		}
		videoIntent.putExtra("OPEN_ID", openIdStr);
		pContext.sendBroadcast(videoIntent);
	}

	/**
	 * 收到照片或者视频， 做处理，是否上传
	 * 
	 * @param context
	 * @param string
	 * @param path
	 * @param open_id
	 */
	public static void upLoadPhotoOrVideo(Context context, String type,
			String path, String openId) {
		L.i("PushOption upLoadPhotoOrVideo-- type==" + type);
		// 加唤醒屏幕锁
		PowerManager powerManager = (PowerManager) context
				.getSystemService(Context.POWER_SERVICE);
		WakeLock wakeLock = powerManager
				.newWakeLock(PowerManager.ON_AFTER_RELEASE
						| PowerManager.FULL_WAKE_LOCK, "");
		wakeLock.acquire();

		// maps 表示传给服务器携带的信息
		Map<String, String> maps = new HashMap<String, String>();
		maps.put("type", "video");
		String open_Id = null; // open_Id为空的时候，表示震动上传
		if (openId != null) {
			open_Id = openId;
		}
		maps.put("openId", open_Id);
		boolean isWarning = false;
		if (Utils.isEmpty(open_Id) && type.equals("getPhoto")) {
			// 判断是否超过半个小时，发送一次成功后，半个小时内只发一张
			if (Utils.isAboveTime(wakeLock)) {
				L.i("no more 30minute ");
				return;
			}
			isWarning = true;
			String token = ServerRequest.getCustomToken(MyApplication.customId);
			L.i("PushOption upLoadPhotoOrVideo-- token==" + token);
			maps.put("access_token", token);
		}
		maps.put("imei", Utils.getImei(context));
		maps.put("lat", String.valueOf(MyLocationListener.lat));
		maps.put("lon", String.valueOf(MyLocationListener.lon));
		final Map<String, String> fileMap = new HashMap<String, String>();
		fileMap.put("str", path);
		// i 表示上传次数
		int i = 3;
		String result = HttpUtil.activeUploadMedia(maps, fileMap, type,
				isWarning);
		while (!result.equals("{success:true}") && i > 0) {
			result = HttpUtil.activeUploadMedia(maps, fileMap, type, isWarning);
			i--;
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		L.i("PushOption upLoadPhotoOrVideo-- result==" + result);

		// 震动图片上传失败，那么下一次震动继续上传
		if (Utils.isEmpty(open_Id) && type.equals("getPhoto")) {
			if (!result.equals("{success:true}")) {
				Utils.lastUploadTime = 0;
			}
		}
	}

	/**
	 * 机器锁定
	 * 
	 * @param obj
	 * @param pContext
	 * @param myHandler
	 */
	public static void openLauncher(JSONObject obj, Context pContext,
			MyHandler myHandler) {
		try {

			Settings.System.putInt(pContext.getContentResolver(),
					"is_user_lock", 0);
			myHandler.sendEmptyMessage(MyHandler.OPENLAUNCHER);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static void closeLauncher(JSONObject obj, Context pContext,
			MyHandler myHandler) {
		try {

			Settings.System.putInt(pContext.getContentResolver(),
					"is_user_lock", 1);
			myHandler.sendEmptyMessage(MyHandler.CLOSELAUNCHER);
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	public static void startVideo(JSONObject obj,final MyHandler myHandler) {
		final String path;
		try {
			path = obj.getString("value");
			L.i("path==" + path);
			
			new Thread(new Runnable() {

				@Override
				public void run() {
					String fileName = HttpUtil.downloadVideo(path);
					Message msg = new Message();
					msg.what = MyHandler.DOWNLOADVIDEOCOMPLETE;
					msg.obj = fileName;
					myHandler.sendMessage(msg);

				}

			}).start();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

}
